<?php

namespace App\Console\Commands;

use App\Models\BookIsbn;
use App\Models\Goods;
use Illuminate\Console\Command;

class RepairGoodCommand extends Command {
	/**
	 * The name and signature of the console command.
	 *
	 * @var string
	 */
	protected $signature = 'system:good {id?}';

	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = 'Command description';

	/**
	 * Create a new command instance.
	 *
	 * @return void
	 */
	public function __construct() {
		parent::__construct();
	}

	/**
	 * Execute the console command.
	 *
	 * @return mixed
	 */
	public function handle() {

		$id = $this->argument('id');
		if ($id) {
			$good = Goods::find($id);
			$this->update($good);
		} else {
			$isbns = BookIsbn::where('title', 'like', '中国%')->get();

			foreach ($isbns as $good) {
				$titlelength = mb_strlen($good->title, 'utf8');
				if ($titlelength < 4) {
					print $good->title . "标题太短，跳过\n";
					continue;
				}

				print($good->id . "\n");
				if (empty($good->title)) {
					continue;
				}
				if (empty($good->pubdate) || empty($good->publisher)) {
					print $good->title . "isbn商品出版为空，跳过\n";
					continue;
				}
				$this->update($good, true);

			}
		}

	}

	public function update($good, $all = false) {
		$notIsbnGoods = Goods::where('title', 'like', "{$good->title}%")->where('isbn', '10')->get();
		$titleLen = mb_strlen($good->title, 'utf8') * 3;
		$reg = '/^([\x{4e00}-\x{9fa5}]|[\s\da-zA-Z])+\++/u';

		foreach ($notIsbnGoods as $value) {

			$pub = ['name' => $good->title, 'basedate' => $good->pubdate, 'basepress' => $good->publisher,
				'pubdate' => $value->pubdate, 'press' => $value->press,
			];

			print($value->item_id . "\n");
			print($value->title . "\n");
			if (empty($value->pubdate) && empty($value->press)) {
				var_dump($pub);

				print("出版为空，跳过\n");
				continue;
			}
			if (!empty($value->pubdate)) {

				$pubdate = strpos($good->pubdate, $value->pubdate);
				if (!$pubdate) {
					$pubdate2 = explode('-', $good->pubdate);
					$pubdate3 = explode('-', $value->pubdate);
					if (count($pubdate3) == 2 && count($pubdate2) == 2) {
						if ($pubdate2[0] == $pubdate3[0] && $pubdate2[1] == $pubdate3[1]) {
							return true;
						}
					}
				}
			} else {
				$pubdate = false;
			}

			if (!empty($value->press)) {
				$pubdate1 = $all == true ? $good->publisher : $good->press;
				$press = strpos($pubdate1, $value->press);

			} else {
				$press = false;
			}

			if ($pubdate === false && $press === false) {
				var_dump($pub);
				print("出版不对,跳过这个商品\n");
				continue;
			}
			// if (mb_strlen($value->title, 'utf8') > $titleLen) {
			//     print("标题太长,跳过这个商品\n");
			//     continue;
			// }
			if (preg_match($reg, $value->title)) {
				print("标题不对，跳过这个商品\n");
				continue;
			}
			print "========================\n";

			$value->isbn = $good->isbn13;
			$a = $value->save();

			var_dump($a, $value->id, $good->isbn13);
			print "========================\n";
		}
	}
}
